package com.xxx.filedownload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FileServer {

	public static void main(String[] args) {

		ServerSocket serverSocket = null;
		Socket accept = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		FileInputStream fis = null;
		FileOutputStream fos = null;
		{
			try {
				//创建服务端
				serverSocket = new ServerSocket(9999);
				//获取客户端连接
				accept = serverSocket.accept();
				//收到下载文件请求
				inputStream = accept.getInputStream();

				byte[] b = new byte[1024];

				inputStream.read(b);
						//文件名
				String fileName = new String(b);
				System.out.println("客户端要下载的文件名字是：" + fileName);

				//拿到这个文件名之后，找到文件所在路径
				//向客户端输出
				outputStream = accept.getOutputStream();
				String filePath = "E:\\图片\\动漫\\97442170_p0_master1200.jpg";
				System.out.println(filePath);

				//获取文件
				File file = new File(filePath);

				fis = new FileInputStream(file);

				int len;
				byte[] bytes = new byte[1024];
				while ((len = fis.read(bytes)) != -1) {

					outputStream.write(bytes);

				}


			} catch (IOException e) {
				e.printStackTrace();
			}finally {


				try {
					if (fos != null) {
						fos.close();
					}
					if (fis != null) {
						fis.close();
					}
					if (outputStream != null) {
						outputStream.close();
					}
					if (inputStream != null) {
						inputStream.close();
					}
					if (accept != null) {
						accept.close();
					}
					if (serverSocket != null) {
						serverSocket.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}

	}

}
